from collections import defaultdict

import numpy as np
from django.http import QueryDict

from permissions.model_serializers import PermissionSerializer
from permissions.models import PermissionUser
from utils.mixins.common_mixins.logger import common_logger


class PermissionService:

    @staticmethod
    def get_dict_type_permissions(user, filters=None):
        """
        获取用户的权限
        :param user:
        :return:
        """
        if filters is None:
            filters = {}
        if isinstance(filters, QueryDict):
            filters = filters.dict()
        common_logger.info(f'filters: {filters} {dict(filters)}')
        generic_permissions = np.array(
            [g.gp.filter(is_deleted=False, **filters) for g in user.permissiongroup_set.all()]).flatten()

        dict_type_permission = defaultdict(dict)

        for gps in generic_permissions:
            for gp in gps:
                p = gp.content_object
                p_code = f"{p.code}__{p._meta.model_name}"
                _data = PermissionSerializer(gp).data
                dict_type_permission[p_code][_data['code']] = _data

        generic_permissions = PermissionUser.objects.get(id=user.id).gp.filter(is_deleted=False, **filters)

        for gp in generic_permissions:
            p = gp.content_object
            p_code = f"{p.code}__{p._meta.model_name}"
            _data = PermissionSerializer(gp).data
            dict_type_permission[p_code][_data['code']] = _data

        return dict_type_permission

    @classmethod
    def get_permission(cls, user, per_name, **filters):
        permissions = cls.get_dict_type_permissions(user, filters=filters)
        common_logger.info(f'permissions: {permissions}')
        return permissions.get(per_name, {})

    @classmethod
    def get_permissions(cls, user, per_names, **filters):
        permissions = cls.get_dict_type_permissions(user, filters=filters)
        return {per_name: permissions.get(per_name, {}) for per_name in per_names}
